package com.cch.cooperation.common.web.interceptors;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.cch.cooperation.common.web.enums.AuthorityEnum;
import com.cch.cooperation.common.web.response.Response;
import com.cch.cooperation.common.web.session.Session;
import com.cch.cooperation.common.web.session.SessionManager;
import com.cch.cooperation.common.web.util.RequestUtil;
import com.cch.cooperation.common.web.util.ResponseUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthorityInterceptor implements HandlerInterceptor {

    protected SessionManager userSessionManager;

    public AuthorityInterceptor(SessionManager userSessionManager) {
        this.userSessionManager = userSessionManager;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        return this.checkAuthority(request, response);
    }

    private boolean checkAuthority(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String accessToken = RequestUtil.getAccessToken(request);
        if (StrUtil.isEmpty(accessToken)) {
            Response data = Response.fail(AuthorityEnum.AuthoritySate.ILLEGAL.msg, AuthorityEnum.AuthoritySate.ILLEGAL.statusCode);
            ResponseUtil.resultJson(response, data);
            return false;
        }
        Session session = userSessionManager.get(accessToken);
        if (ObjectUtil.isNull(session)) {
            Response data = Response.fail(AuthorityEnum.AuthoritySate.EXPIRED.msg, AuthorityEnum.AuthoritySate.EXPIRED.statusCode);
            ResponseUtil.resultJson(response, data);
            return false;
        }
        return true;
    }
}
